const { WX_AD_CONFIG } = require("../constants")

module.exports = {
  videoExist: false,
  videoFunc: null,
  interstitialExist: false,
  bannerDict: {},
  bannerLoad: [],

  tmIconDict: {},    // 天幕ICON
  init() {
    this.checkWxVersion()
    this.initVideo()
    this.loadBanner()
    this.loadInterstitial()
  },
  // 视频初始化
  initVideo() {
    if (!WX_AD_CONFIG.videoId) {
      return
    }
    this.ad_Video = wx.createRewardedVideoAd({ adUnitId: WX_AD_CONFIG.videoId })
    this.ad_Video.onLoad(() => {
      this.videoExist = true
    })
    this.ad_Video.onError(() => {
      this.videoExist = false
      this.loadVideo()
    })
    this.ad_Video.onClose(res => {
      if (res && res.isEnded || res === undefined) {
        if (this.videoFunc) {
          he.local.click("load_ad_get")
          this.videoFunc()
          this.loadVideo()
          this.videoFunc = null
        }
      }
    })
  },
  // 视频加载 视频展示
  loadVideo() {
    this.ad_Video.load().then((res) => {
      he.local.click("load_ad_suc")
      this.videoExist = true
    }).catch((error) => {
      this.videoExist = false
    })
  },
  loadInterstitial() {
    if (!WX_AD_CONFIG.interstitialId) {
      return
    }
    if (this.interstitialExist) {
      return
    }
    this.ad_Interstitial = wx.createInterstitialAd({ adUnitId: WX_AD_CONFIG.interstitialId })
    this.ad_Interstitial.onLoad(() => {
      this.interstitialExist = true
    })
    this.ad_Interstitial.onError(err => {
      this.interstitialExist = false
      this.loadInterstitial()
    })
  },
  interstitialShow() {
    if (!this.interstitialExist) {
      this.loadInterstitial()
      return
    }
    this.ad_Interstitial.show()
  },
  showVideo(fuc) {
    if (!this.videoExist) {
      this.loadVideo()
      return
    }
    he.local.click("load_ad_click")
    this.videoFunc = fuc
    this.ad_Video.show()
    this.videoExist = false
  },
  // 加载Banner
  loadBanner() {
    if (!WX_AD_CONFIG.bannerId.length) {
      return
    }
    for (let i = 0; i < WX_AD_CONFIG.bannerId.length; i++) {
      this.bannerDict[WX_AD_CONFIG.bannerId[i]] = wx.createBannerAd({ adUnitId: WX_AD_CONFIG.bannerId[i], adIntervals: 30 })
      this.bannerDict[WX_AD_CONFIG.bannerId[i]].onLoad(() => {
        this.bannerLoad.push(WX_AD_CONFIG.bannerId[i])
      })
      this.bannerDict[WX_AD_CONFIG.bannerId[i]].onError(err => {
        he.error(err)
      })
    }
  },
  // 展示Banner形式
  changeBanner(status, posNode) {
    let bannerId = posNode.name
    if (WX_AD_CONFIG.bannerId.indexOf(bannerId) < 0) {
      he.error("该广告节点妹有")
      return
    }
    if (status) {
      let posSize = cc.size(posNode.width * zoom_scale, posNode.height * zoom_scale);
      let frameSize = cc.view.getFrameSize();
      let winSize = cc.director.getWinSize();
      let worldPos = posNode.convertToWorldSpaceAR(cc.Vec2.ZERO)
      let width = posSize.width / winSize.width * frameSize.width;
      let height = posSize.height / winSize.height * frameSize.height
      let left = (worldPos.x - posSize.width / 2) / winSize.width * frameSize.width
      let top = (winSize.height - worldPos.y - posSize.height / 2) / winSize.width * frameSize.width
      this.bannerDict[bannerId].style.left = left
      this.bannerDict[bannerId].style.top = top
      if (width < 300) {
        he.error("广告预制体小了")
      }
      this.bannerDict[bannerId].style.width = width
      this.bannerDict[bannerId].style.height = height
      this.bannerDict[bannerId].show()
    } else {
      this.bannerDict[bannerId].hide()
    }
  },
  // 展示天幕弹窗
  showTmAd(status, posNode) {
    if (WX_AD_CONFIG.tmIcon.indexOf(tmId) < 0) {
      he.error("该广告节点妹有")
      return
    }
    if (status) {
      let posSize = cc.size(posNode.width * zoom_scale, posNode.height * zoom_scale);
      let worldPos = posNode.convertToWorldSpaceAR(cc.Vec2.ZERO)
      let winSize = cc.director.getWinSize();

      let left = worldPos.x - posSize.width / 2
      let top = winSize.height - worldPos.y - posSize.height / 2

      this.tmIconDict[tmId] = wx.tmSDK.createFlow({
        positionId: tmId,
        x: left,
        y: top,
        width: posSize.width
      });
    } else {
      this.tmIconDict[tmId].destroy()
    }
  },
  getTdAdJson(id, func) {
    wx.tmSDK.getFlowConfig({
      positionId: id
    }).then((config) => {
      if (func) {
        func(config)
      }
    });
  },
  // 删除天幕弹窗
  delAllTm() {
    for (let i = WX_AD_CONFIG.tmIcon.length - 1; i >= 0; i--) {
      let tmId = WX_AD_CONFIG.tmIcon[i]
      if (this.tmIconDict[tmId]) {
        this.tmIconDict[tmId].destroy()
      }
    }
  },
  // 确定当前微信版本是否可以播放广告
  checkWxVersion() {
    var systemInfo = wx.getSystemInfoSync();
    var sdkversion = systemInfo.SDKVersion;
    //激励视频广告版本检测
    let isCanPlayRewardAudio = this.compareVersion(sdkversion, WX_AD_CONFIG.rewardVideoVersion) >= 0;
    //banner广告版本检测
    let isCanShowBanner = this.compareVersion(sdkversion, WX_AD_CONFIG.bannerVersion) >= 0;
    //插屏广告版本检测
    let isCanShowInterstitial = this.compareVersion(sdkversion, WX_AD_CONFIG.interstitialVersion) >= 0;
    if (!isCanShowInterstitial || !isCanShowBanner || !isCanPlayRewardAudio) {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，部分功能无法使用，请升级到最新微信版本后重试。'
      })
    }
  },
  // 版本校对
  compareVersion: function (v1, v2) {
    var firstVersion = v1.split(".");
    var secondVersion = v2.split(".");
    var len = Math.max(firstVersion.length, secondVersion.length);
    while (firstVersion.length < len) {
      firstVersion.push("0");
    }
    while (secondVersion.length < len) {
      secondVersion.push("0");
    }
    for (var i = 0; i < len; i++) {
      var num1 = parseInt(firstVersion[i]);
      var num2 = parseInt(secondVersion[i]);
      if (num1 > num2) {
        return 1;
      } else if (num1 < num2) {
        return -1
      }
    }
    return 0;
  },

}